﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace OISTools
{
    public partial class SmartEditer : Form
    {
        public SmartEditer()
        {
            InitializeComponent();
        }

        private void SmartEditer_Load(object sender, EventArgs e)
        {
            System.Threading.Thread td = new System.Threading.Thread(ThreadProcSafe);
            td.Start();
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }


        private void ThreadProcSafe()
        {
            while (true)
            {
                string Context = "";

                System.Func<string> funcQuery = new Func<string>(getText);
                Context = this.Invoke(funcQuery).ToString();

                for (int i = 0; i < Context.Length; i++)
                {
                    if (readText(Context,i, 4) == "exit")
                    {
                        ColorData data = new ColorData() { color = Color.Red, length = 4, startIndex = i };
                        System.Action<object> func1 = new Action<object>(setColor);
                        this.Invoke(func1, new object[] { data });
                    }
                }

            }
        }


        private string readText(string Context, int index, int length)
        {
            if (Context.Length  >= index + length)
            {
                return Context.Substring(index, length);
            }
            else
            {
                return "";
            }
        }

        private string getText()
        {
            return richTextBox1.Text;
        }


        private void setColor(object obj)
        {
            ColorData data = (ColorData)obj;

            int startIndex=data.startIndex;
            int length=data.length;
            Color color = data.color;

            richTextBox1.Select(startIndex, length);
            richTextBox1.SelectionColor = Color.Red;
            richTextBox1.Select(0, 0);
            richTextBox1.SelectionColor = Color.Black;
            richTextBox1.ForeColor = Color.Black;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            richTextBox1.ForeColor = Color.Black;
            richTextBox1.SelectionColor = Color.Black;
        }


    }

    public class ColorData
    {
        public int startIndex;
        public int length;
        public Color color;
    }

}
//private void SetText(string text)
//{
//    if (this.textBox1.InvokeRequired)
//    {
//        SetTextCallback d = new SetTextCallback(Speak);
//        this.Invoke(d, new object[] { text });
//    }
//}